package com.kxr.literetrofit.network.subscriber;

import com.kxr.literetrofit.network.baseresponse.BaseResponse;
import com.kxr.literetrofit.network.translator.IDataTranslator;
import com.kxr.literetrofit.network.translator.SimpleTranslator;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by kongxr on 2019/3/12.
 * 数据观察者（数据初步处理）
 * 使用默认格式转换器
 * 当服务器返回数据格式为XindunResponse<T>时使用此回调
 */
public abstract class SimpleObserver<T> implements Observer<ResponseBody> {

    private IDataTranslator<BaseResponse<T>> simpleTranslator;

    //此方式会将返回数据自动解析为XindunResponse<class>形式回调到onsuccess
    protected SimpleObserver(Class clazz) {
        simpleTranslator = new SimpleTranslator<T>(clazz);
    }

    //一般情况，默认选择无参构造，此方式会将返回数据自动解析为XindunResponse<String>形式回调到onsuccess
    protected SimpleObserver() {
        simpleTranslator = new SimpleTranslator<T>();
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    //一般情况下不要复写此方法，使用onSuccess获取结果
    @Override
    public void onNext(ResponseBody responseBody) {
        BaseResponse<T> result;
        try {
            result = simpleTranslator.translate(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            onError(e);
            return;
        }
        onSuccess(result);
    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }

    //复写此方法获取请求结果
    protected abstract void onSuccess(BaseResponse<T> responseBean);
}
